const db = require('./db');
const vertoken = require('./token')

const dbQuery = async (query) => {
    return await new Promise((resolve, reject) => {
        db.query(query, function(err, data) {
            if (err) {
                reject(err);
                return;
            }
            resolve(data);
        });
    });
}
const dbError = (res, error, message = '数据库错误') => {
    console.log(error);
    res.status(500).send({code: 0, message, error: error.sqlMessage});
}
const updateToken = (res, data, id, obj = {code: 1, message: '更新成功'}) => {
    if (data) {
        return vertoken.setToken(data).then(token => {
            res.send({...obj, data, token});
        });
    }
    dbQuery(`select id,account,name,gender,introduction,avator,can_create from user_table where id='${id}'`)
    .then(data => {
        vertoken.setToken(data[0]).then(token => {
            res.send({...obj, data: data[0], token});
        });
    })
    .catch(err => {
        dbError(res, err, '获取信息失败');
    })
}
const sqlStrQuotationHandle = str => str.replace(/'/g, "''").replace(/"/g, '""');


module.exports = {
    dbQuery,
    dbError,
    updateToken,
    sqlStrQuotationHandle
}
